import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Router } from '@angular/router';
import { Util } from './util';
import { AppSettings } from '../app.settings';
import { Scope } from './emit';

@Injectable()
export class AuthService {

  // 全局保存userInfo
  private user: any = {"id":5,"nick":"xxxx","regDate":1481163958000,"lastLogin":1512545590283,"loginTimes":2013,"eid":0,"status":"1","channel":0,"versionId":523,"activeVersionInfo":{"id":523,"version":"3","category":-1,"deadLine":1527955200000,"userId":5,"catName":"/","catCount":1,"itemLimit":20,"brandLimit":5,"downloadLimit":5,"catRefreshLimit":1,"shopCount":50,"productCount":50,"brandCount":50,"categoryCount":40,"netRed":true,"onlineCount":1,"authority":"3"},"contact":null,"authorities":[{"id":523,"version":"3","category":-1,"deadLine":1527955200000,"userId":5,"catName":"/","catCount":1,"itemLimit":20,"brandLimit":5,"downloadLimit":5,"catRefreshLimit":1,"shopCount":50,"productCount":50,"brandCount":50,"categoryCount":40,"netRed":true,"onlineCount":1,"authority":"3"}],"accountNonExpired":true,"accountNonLocked":true,"credentialsNonExpired":true,"enabled":true,"username":"xxxx"};

  constructor(private http: Http, private router: Router, private util: Util, private scope: Scope, private appSettings: AppSettings) { 
    this.util.sessionStore().set('user',this.user);
  }


  logout() {
    return new Promise((resolve, reject) => {

      this.http.post('/qbmf/signOut', { 'body': {} }).subscribe(
        (res: any) => {

          this.util.sessionStore().delete('user');

          // 云起渠道
          if (window.localStorage.getItem('channel') === '1') {

            window.location.href = "http://yunqi.shopex.cn/";
          }
          //
          else {
            this.router.navigate(['/login']);
          }



        },
        (res: any) => {
          console.log(res);
          console.log('eerrr');
          // this.router.navigate(['/login']);
          reject();
        },
        () => { }
      );

    });
  }


  // return promise user
  isLogin() {

    // console.table(this.user);

    return new Promise((resolve, reject) => {
      // 用户已存在
      if (this.util.sessionStore().has('user')) {
        console.log('用户已经登录');

        this.user = this.util.sessionStore().get('user');

        resolve(this.user);

      } else {
        // 获取用户
        this.http.get('/qbmf/api/user').subscribe(
          (res: any) => {
            // console.log('data--getUser');

            // console.log(res);

            if (res.code == 0) {


              this.user = res.data;


              // 设置类目
              this.appSettings.roleNavInit(this.user);

              // 存储channel
              let channel: string = this.user.channel;

              window.localStorage.setItem('channel', channel);

              this.util.sessionStore().set("user", this.user);


              // 广播user
              // this.scope.emit('UserLoginEvent',this.user);


              resolve(this.user);
            } else {
              reject();
            }
          },
          (res: any) => {
            console.log(res);
            console.log('eerrr');
            // this.router.navigate(['/login']);
            reject();
          },
          () => { }
        );
      }
    });

  }

  getUserInfo(): any {
    alert(1);
    return new Promise((resolve, reject) => {
      if (this.util.isEmptyObject(this.user)) {
        reject(false);
      } else {
        resolve(this.user);
      }

    });

  }



  destroy() {
    this.user = {};
  }
}
